import {Component, ComponentProps, VueComponent, Link, Hook, Mut, Computed} from "vue3-oop";
import {NButton, NButtonGroup, NSpace, NDropdown, NScrollbar} from "naive-ui";
import BpmnModeler from '../BpmnModeler';

import Codemirror from "codemirror-editor-vue3";
import 'codemirror/theme/monokai.css'
import 'codemirror/mode/javascript/javascript.js';
import 'codemirror/mode/xml/xml.js';

import newBpmnXml from './newBpmnXml';

interface IProps {
  bpmnModeler: BpmnModeler
}
@Component()
export default class ToolbarPanel extends VueComponent<IProps> {
  static defaultProps: ComponentProps<IProps> = {
    bpmnModeler:{},
  }

  constructor() {
    super()
  }

  /** 预览BPMN的XML内容 */
  private handlePreviewBpmn=()=>{
    const xml = this.props.bpmnModeler.getGraphXml();
    const dialog = window.$popUp({
      style: {width:`${window.$size.width-200}px`,height:`${window.$size.height-200}px`,padding:"10px"},
      title: "BPMN预览",
      content:()=>(
        <NScrollbar style={{maxHeight:`${window.$size.height-250}px`}} xScrollable={true}>
          <Codemirror
            value={xml}
            border
            options={{
              mode: 'xml', // 语言模式
              theme: 'darcula', // 主题
              lineNumbers: false, // 显示行号
              // smartIndent: true, // 智能缩进
              // readOnly: true,
              // indentUnit: 4, // 智能缩进单位为4个空格长度
              foldGutter: false, // 启用行槽中的代码折叠
              styleActiveLine: true // 显示选中行的样式
            }}
          />
        </NScrollbar>
      )
    });
  }

  /** 导入文件 */
  private handleImportBpmnFile =()=>{
    const input = document.createElement('input');
    input.value = '选择文件';
    input.type = 'file';
    input.accept = 'application/xml';
    input.onchange = (event:any) => {
      if(event.target.files.length>0){
        const reader = new FileReader();
        reader.readAsText(event.target.files[0]);
        reader.onload = ()=>{
          this.props.bpmnModeler.setGraphXml(reader.result as string);
        };
      }
    };
    input.click();
  }

  /** 导出文件 */
  private handleExportFile=(type:'PNG'|'JPEG'|'SVG'|'BPMN')=>{
    const { bpmnModeler } = this.props;
    const xml = bpmnModeler.getGraphXml();
    const processId = bpmnModeler.processProps.id;
    const processName = bpmnModeler.processProps.name;
    const today = new Date();
    const year = today.getFullYear(), month = today.getMonth()+1, date = today.getDate();
    const hours = today.getHours(), minutes = today.getMinutes(), seconds = today.getSeconds();
    const fix=(num:any)=>num<10?('0'+num):num;
    const time = `${year}${fix(month)}${fix(date)}_${fix(hours)}${fix(minutes)}${fix(seconds)}`;
    const filename = `${processName}[${processId}].${time}`
    if(type==='PNG'){
      bpmnModeler.getGraph().exportPNG(`${filename}.png`,{padding:20});
    }else if(type==='JPEG'){
      bpmnModeler.getGraph().exportJPEG(`${filename}.jpeg`,{padding:20});
    }else if(type==='SVG'){
      bpmnModeler.getGraph().exportSVG(`${filename}.svg`,{});
    }else{
      const downlink = `data:text/plain;charset=UTF-8,${encodeURIComponent(xml)}`;
      const a = document.createElement("a");
      a.download = `${filename}.bpmn20.xml`; //指定下载的文件名
      a.href = downlink; //  URL对象
      a.click(); // 模拟点击
      URL.revokeObjectURL(a.href); // 释放URL 对象
    }
  }

  @Hook("Mounted")
  onMounted(){
    const { bpmnModeler } = this.props;
    const currentRoute = window.$router.currentRoute.value;
    const definitionId = currentRoute.params.id;
    if(!definitionId||definitionId.length===0||definitionId==="new"){
      bpmnModeler.setGraphXml(newBpmnXml);
    }else{
      window.$http.get(`/api/workflow/definition/deployment/${definitionId}`).then(({data:responseBody})=>{
        if(responseBody.success){
          bpmnModeler.setGraphXml(responseBody.record.bpmnXml);
        }
      })
    }

  }

  private handleDeployBpmnFile=()=>{
    const { bpmnModeler } = this.props;
    const xml = bpmnModeler.getGraphXml();
    const processId = bpmnModeler.processProps.id;
    const processName = bpmnModeler.processProps.name;
    const today = new Date();
    const year = today.getFullYear(), month = today.getMonth()+1, date = today.getDate();
    const hours = today.getHours(), minutes = today.getMinutes(), seconds = today.getSeconds();
    const fix=(num:any)=>num<10?('0'+num):num;
    const time = `${year}${fix(month)}${fix(date)}_${fix(hours)}${fix(minutes)}${fix(seconds)}`;
    const filename = `${processName}[${processId}].${time}.bpmn20.xml`
    const form = new FormData();
    form.append("filename", filename);
    form.append("content",xml);
    window.$http.post('/api/workflow/definition/deploy',form,{headers:{"Content-Type": "multipart/form-data"}}).then(({data})=>{
      if(data.success){
        window.$message.success(data.message);
      }
    })
  }

  render(){

    return(
      <NSpace>
        <NButtonGroup size={"small"}>
          <NButton onClick={this.handlePreviewBpmn}>预览</NButton>
          <NButton onClick={this.handleImportBpmnFile}>导入</NButton>
          <NDropdown
            size="small"
            options={[
              {key:'PNG',label:'PNG',props:{onClick:()=>{this.handleExportFile('PNG')}}},
              {key:'JPEG',label:'JPEG',props:{onClick:()=>{this.handleExportFile('JPEG')}}},
              // {key:'SVG',label:'SVG',props:{onClick:()=>{this.handleExportFile('SVG')}}}
            ]}
          >
            <NButton onClick={()=>{this.handleExportFile('BPMN')}}>导出</NButton>
          </NDropdown>
          <NButton onClick={this.handleDeployBpmnFile}>部署</NButton>
        </NButtonGroup>
      </NSpace>
    )
  }
}